package com.sth.shishan;

import org.junit.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.ListPosition;

import java.util.List;
import java.util.Random;

/**
 * @Author: sitianhong
 * @Description: 实现OA系统中的代办事项列表管理
 * @Since: create in 2021/6/13 0013 18:14
 */
public class RedisDemo6 {
    Jedis jedis = new Jedis("127.0.0.1", 6378);

    @Test
    public void demo1() {
        for (int i = 0; i < 20; i++) {
            addTodoEvent(1, "第 " + (i + 1) + "代办事项");
        }
        int pageNo = 1;
        int pageSize = 10;
        List<String> todoEventByPage = findTodoEventByPage(1, pageNo, pageSize);
        System.out.println("初始化的" + todoEventByPage.toString());

        // 插入代办事项
        Random random = new Random();
        int index = random.nextInt(todoEventByPage.size());
        System.out.println(index);
        String targetTodoEvent = todoEventByPage.get(index);
        insertTodoEvent(1, ListPosition.BEFORE, targetTodoEvent, "插入的代办事项");
        List<String> todoEventByPage2 = findTodoEventByPage(1, pageNo, pageSize);
        System.out.println("插入了一个" + todoEventByPage2.toString());
    }

    // 添加代办事项
    public void addTodoEvent(long userId, String totoEvent) {
        jedis.lpush("todo_event::" + userId, totoEvent);
    }

    public List<String> findTodoEventByPage(long userId, int pageNo, int pageSize) {
        int startIndex = (pageNo - 1) * pageSize;
        int endIndex = pageNo * pageSize - 1;
        return jedis.lrange("todo_event::" + userId, startIndex, endIndex);
    }

    // 插入代办事项
    public void insertTodoEvent(long userId, ListPosition position, String todoEvent, String targetTodoEvent) {
        Long linsert = jedis.linsert("todo_event::" + userId, position, targetTodoEvent, todoEvent);
        System.out.println("linsert " + linsert);
    }

    // 完成一个代办事项
    public void finishTodoEvent(long userId, String todoEvent) {
        jedis.lrem("todo_event::" + userId, 0, todoEvent);
    }

    // 修改代办事项
    public void updateTodoEvent(long userId, int index, String updateTodoEvent) {
        jedis.lset("todo_event::" + userId, 0, updateTodoEvent);
    }

}
